package util;

import com.mchange.v2.c3p0.ComboPooledDataSource;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;

public class DataSourceUtils {
    private static DataSource dataSource= new ComboPooledDataSource();
    private static ThreadLocal<Connection> tl = new ThreadLocal<Connection>();
    //获取数据库连接池
    public static DataSource getDataSource(){
        return dataSource;
    }
    //获得一个数据库连接
    public static Connection getConnection() throws SQLException{
        //得到线程连接对象
        Connection con = tl.get();
        if (con==null){
            con = dataSource.getConnection();
            tl.set(con);
        }
        return con;
    }

    //开启事务
    public static void startTransaction() throws SQLException{
        Connection con = getConnection();
        if (con == null) {
            con.setAutoCommit(false);
        }
    }

    //关闭事务
    public static void releaseAndCloseConnection() throws SQLException{
        Connection con = getConnection();
        if (con != null) {
            con.setAutoCommit(false);
            con.commit();
            tl.remove();
            con.close();
        }
    }

    //事务回滚
    public static void rollback() throws  SQLException{
        Connection con = getConnection();
        if (con != null) {
            con.setAutoCommit(false);
            con.rollback();
        }
    }
}
